package com.block.datapush.service.apipush;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.block.common.enums.ProfitSharingEnum;
import com.block.common.model.param.PushApiKeyParam;
import com.block.common.service.LogFactory;
import com.block.common.service.impl.ApplicationInfoServiceImpl;
import com.block.datapush.enums.PushStatusEnum;
import com.block.datapush.model.PushQueryParam;
import com.block.datapush.model.dto.NoticeParamDTO;
import com.block.datapush.model.result.ProtocolParamResult;
import com.block.datapush.model.result.PushApiResult;
import com.block.datapush.service.IPushApiService;
import com.block.datapush.service.apipush.utils.HaoXinHuaUtil;
import com.block.db.entity.*;
import com.block.db.mapper.DataMatchOrderItemMapper;
import com.block.db.mapper.MerchantDataPushInfoMapper;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.math.BigDecimal;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 好鑫花
 */
@Service
public class HaoXinHuaApiBRatePushService implements IPushApiService {

    private static final Logger log = LogFactory.getPushLog();


    @Autowired
    MerchantDataPushInfoMapper merchantDataPushInfoMapper;
    @Autowired
    ApplicationInfoServiceImpl applicationInfoService;

    @Autowired
    DataMatchOrderItemMapper dataMatchOrderItemMapper;


    @Override
    public PushApiResult checkUser(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {

        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        String queryUrl = pushApiKeyParam.getCheckUrl();
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("phoneMd5", memberSourceInfo.getMobileMd5().toLowerCase());
        paramMap.put("userName", memberSourceInfo.getRealname());
        paramMap.put("sex", memberSourceInfo.getSex() ==1 ?  1 : 0);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("zhimaCredit", HaoXinHuaUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("fund", HaoXinHuaUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("has", HaoXinHuaUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("bdStatus", HaoXinHuaUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("houseProperty", HaoXinHuaUtil.getHouse(memberSourceInfo.getHouse()));
        Integer car = HaoXinHuaUtil.getCar(memberSourceInfo.getCar());
        paramMap.put("carProperty", car);
        if(StrUtil.equals(String.valueOf(car), "2")){
            paramMap.put("mortgageStatus",2);
            paramMap.put("vehicleAge", 1);
            paramMap.put("vehicleValue", 1);
            paramMap.put("licensePlateArea", "未知");
        }
        paramMap.put("professional", HaoXinHuaUtil.getJob(memberSourceInfo.getGongzuo()));
        paramMap.put("enterpriseLicense", 1);
        paramMap.put("loanAmount", HaoXinHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("registerIp", HaoXinHuaUtil.getIp(memberSourceInfo.getReqIp()));
        paramMap.put("platform", 1);
        paramMap.put("monthlyIncome", HaoXinHuaUtil.getShouru(memberSourceInfo.getShouru()));

        String content = JSON.toJSONString(paramMap);
        String aesContent = getAesEncrypt(pushApiKeyParam.getApiSecret(),content);
        String serialNo = UUID.randomUUID().toString();
        HashMap<String, Object> aceMap = new HashMap<>();
        aceMap.put("content",aesContent);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("serialNo",serialNo);

        log.info("【好鑫花半流程分润】撞库开始【queryUrl】{}【paramMap】{} 【aceMap】{}", queryUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(queryUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【好鑫花半流程分润】撞库结束【result】{}", result);


        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");


        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            JSONObject data = resultObject.getJSONObject("data");
            String url = data.getString("url");
            String applyNo = data.getString("applyNo");
            pushApiResult.setApproveUrl(url);
            pushApiResult.setOutOrderNo(applyNo);
            pushApiResult.setStatus(PushStatusEnum.WAIT_APPROVE.getValue());
            pushApiResult.setSettleFlag(true);
            pushApiResult.setPushSuccess(true);
            extJson.put("applyNo",applyNo);
            //进行分润操作
            String priceType = pushApiKeyParam.getPriceType();
            BigDecimal typeRate = pushApiKeyParam.getTypeRate();
            if(ProfitSharingEnum.PROFITPRICE.getValue().equals(priceType)){
                BigDecimal price = data.getBigDecimal("price");
                if(price == null || price.compareTo(new BigDecimal(0.00))== -1){
                    pushApiResult.setPushSuccess(false);
                    return pushApiResult;
                }
                BigDecimal priceRight = typeRate.multiply(price);
                pushApiResult.setPrice(price);
                pushApiResult.setPriceRight(priceRight);
            }
            return pushApiResult;
        }

        return pushApiResult;
    }

    private String getAesEncrypt(String apiSecret, String data) throws Exception {
        byte[] keyBytes = apiSecret.getBytes(StandardCharsets.UTF_8);
        SecretKeySpec secretKeySpec = new SecretKeySpec(keyBytes, "AES");

        // 创建Cipher实例
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 执行加密
        byte[] encryptedData = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));

        // 将加密后的数据转换为Base64字符串
        return  Base64.getEncoder().encodeToString(encryptedData);
    }


    @Override
    public PushApiResult queryApprove(String orderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        pushApiResult.setOrderNo(orderNo);
        return pushApiResult;
    }

    @Override
    public PushApiResult registerUser(String orderNo, String outOrderNo, PushApiKeyParam pushApiKeyParam, MemberSourceInfo memberSourceInfo, JSONObject extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);

        String requestUrl = pushApiKeyParam.getRegisterUrl();
        Map<String, Object> paramMap = new HashMap<>();
        String applyNo = extJson.getString("applyNo");
        paramMap.put("applyNo", applyNo);
        paramMap.put("phone", memberSourceInfo.getMobile());
        paramMap.put("userName", memberSourceInfo.getRealname());
        paramMap.put("sex", memberSourceInfo.getSex() ==1 ?  1 : 0);
        paramMap.put("age",memberSourceInfo.getAge());
        paramMap.put("city", memberSourceInfo.getCity());
        paramMap.put("cityCode",memberSourceInfo.getCityCode());
        paramMap.put("zhimaCredit", HaoXinHuaUtil.getZhimaScore(memberSourceInfo.getZhima()));
        paramMap.put("fund", HaoXinHuaUtil.getGjj(memberSourceInfo.getGjj()));
        paramMap.put("has", HaoXinHuaUtil.getSocialInsurance(memberSourceInfo.getShebao()));
        paramMap.put("bdStatus", HaoXinHuaUtil.getbaodan(memberSourceInfo.getBaoxian()));
        paramMap.put("houseProperty", HaoXinHuaUtil.getHouse(memberSourceInfo.getHouse()));
        Integer car = HaoXinHuaUtil.getCar(memberSourceInfo.getCar());
        paramMap.put("carProperty", car);
        if(StrUtil.equals(String.valueOf(car), "2")){
            paramMap.put("mortgageStatus",2);
            paramMap.put("vehicleAge", 1);
            paramMap.put("vehicleValue", 1);
            paramMap.put("licensePlateArea", "未知");
        }
        Integer job = HaoXinHuaUtil.getJob(memberSourceInfo.getGongzuo());
        paramMap.put("professional", job);
        if(StrUtil.equals(String.valueOf(car), "3") || StrUtil.equals(String.valueOf(car), "4")){
            paramMap.put("enterpriseLicense", 1);
        }
        paramMap.put("loanAmount", HaoXinHuaUtil.getloan(memberSourceInfo.getLoanAmount()));
        paramMap.put("registerIp", HaoXinHuaUtil.getIp(memberSourceInfo.getReqIp()));
        paramMap.put("platform", 1);
        paramMap.put("monthlyIncome", HaoXinHuaUtil.getShouru(memberSourceInfo.getShouru()));
        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(String.valueOf(pushApiKeyParam.getInfoId()), outOrderNo);
        DataMatchOrderItem dataMatchOrderItem = dataMatchOrderItemMapper.selectDataMatchOrderItemStatus(String.valueOf(entityByOutOrderNoLock.getId()), String.valueOf(pushApiKeyParam.getInfoId()));

        String orderId = String.valueOf(dataMatchOrderItem.getOrderId());
        String orderItemId = String.valueOf(dataMatchOrderItem.getId());
        ApplicationInfo appInfoByAppCode = applicationInfoService.getAppInfoByAppCode(memberSourceInfo.getAppCode());
        String protocolUrl = StrUtil.format("{}/page/newprotocol/{}/{}.html", appInfoByAppCode.getApiUrl(), orderId, orderItemId);
        JSONArray jsonArray = new JSONArray();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("protocolName","安易融授权协议");
        jsonObject.put("protocolUrl",protocolUrl);
        jsonArray.add(jsonObject);
        paramMap.put("protocolList", jsonArray);

        String content = JSON.toJSONString(paramMap);
        String aesContent = getAesEncrypt(pushApiKeyParam.getApiSecret(),content);
        String serialNo = UUID.randomUUID().toString();
        HashMap<String, Object> aceMap = new HashMap<>();
        aceMap.put("content",aesContent);
        aceMap.put("channelCode",pushApiKeyParam.getApiCode());
        aceMap.put("serialNo",serialNo);

        log.info("【好鑫花半流程分润】导单开始【requestUrl】{}【paramMap】{}【aceMap】{}", requestUrl, JSON.toJSONString(paramMap),JSON.toJSONString(aceMap));
        String result = HttpUtil.createPost(requestUrl)
                .header("Content-Type", "application/json")
                .body(JSON.toJSONString(aceMap))
                .execute().body();
        log.info("【好鑫花半流程分润】导单结束【result】{}", result);

        JSONObject resultObject = JSON.parseObject(result);
        Integer code = resultObject.getInteger("code");
        String msg = resultObject.getString("msg");

        pushApiResult.setCode(code + "");
        pushApiResult.setMessage(msg);
        pushApiResult.setParamInfo(JSON.toJSONString(paramMap));
        pushApiResult.setResultInfo(result);

        if (StrUtil.equals(String.valueOf(code), "200")) {
            pushApiResult.setPushSuccess(true);
            pushApiResult.setSettleFlag(true);
            pushApiResult.setStatus(PushStatusEnum.SUCCESS.getValue());
            return pushApiResult;
        }
        pushApiResult.setPushSuccess(false);
        pushApiResult.setSettleFlag(false);
        pushApiResult.setStatus(PushStatusEnum.FAILED.getValue());
        return pushApiResult;
    }

    @Override
    public PushApiResult queryResult(PushQueryParam pushQueryParam, PushApiKeyParam pushApiKeyParam, String extJson) throws Exception {
        PushApiResult pushApiResult = new PushApiResult();
        pushApiResult.setPushSuccess(false);
        return pushApiResult;
    }

    @Override
    public NoticeParamDTO getNoticeResultParam(String infoId, Map<String, String[]> parameterMap, String paramContent) {
        NoticeParamDTO noticeParamDTO = new NoticeParamDTO();

        noticeParamDTO.setOutFlag(true);
        noticeParamDTO.setSettleFlag(true);
        noticeParamDTO.setStatus(PushStatusEnum.SUCCESS.getValue());
        noticeParamDTO.setQueryResult(paramContent);
        JSONObject jsonObject = JSON.parseObject(paramContent);
        if (ObjectUtil.isEmpty(jsonObject)){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
            return noticeParamDTO;
        }
        String applyNo = jsonObject.getString("applyNo");

        MerchantDataPushInfo entityByOutOrderNoLock = merchantDataPushInfoMapper.getEntityByOutOrderNoLock(infoId, String.valueOf(applyNo));
        if (ObjectUtil.isEmpty(entityByOutOrderNoLock) || PushStatusEnum.SUCCESS.getValue().equals(entityByOutOrderNoLock.getStatus())){
            noticeParamDTO.setStatus(PushStatusEnum.CALLBACK_FAILED.getValue());
        }
        noticeParamDTO.setOutOrderNo(applyNo);
        noticeParamDTO.setMerchantDataPushInfo(entityByOutOrderNoLock);
        return noticeParamDTO;

    }

    @Override
    public JSONObject getNoticeResultReturn(Map<String, String[]> parameterMap, String paramContent, JSONObject extObject) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", 200);
        jsonObject.put("msg", "success");
        return jsonObject;
    }


    @Override
    public ProtocolParamResult getProtocolResult(MerchantBaseInfo merchantBaseInfo, MemberSourceInfo memberSourceInfo) {
        return null;
    }

}
